package com.exam.sacrifice.util;

import android.os.Build;

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {
    private static final String AES = "AES";
    private static final String AES_CBC_PKCS5PADDING = "AES/CBC/PKCS5Padding";
    private static final String CHARSET = "UTF-8";

    // 初始化向量，AES CBC模式需要这个参数
    private static final byte[] ivBytes = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    private static IvParameterSpec iv = new IvParameterSpec(ivBytes);

    // 加密方法
    public static String encrypt(String key, String value) {
        SecretKeySpec secretKey = null;
        try {
            secretKey = new SecretKeySpec(key.getBytes(CHARSET), AES);

            Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
            byte[] encrypted = cipher.doFinal(value.getBytes(CHARSET));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                return Base64.getEncoder().encodeToString(encrypted);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    // 解密方法
    public static String decrypt(String key, String encrypted) {
        try {
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(CHARSET), AES);
            Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
            byte[] original = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                original = cipher.doFinal(Base64.getDecoder().decode(encrypted));
            }
            return new String(original, CHARSET);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}